<template>
	<view class="bodyView" :data-theme="dataTheme">
		<view class="blueTest">

			<view class="top">
				<view class="info">
					<view class="inputLine">
						IME:
						<input class="inputIME" v-model="imeV" :adjust-position="false" type="text" placeholder="IME" />
					</view>
					<!-- <view class="inputLine">
						BTK:
						<input class="inputIME" v-model="btkV" :adjust-position="false" type="text" placeholder="蓝牙token" />
					</view>
					 -->
				</view>
				<view class="buttons">
					<!-- <button class="mini-btn" type="primary" size="mini">搜索设备</button> -->
					<button class="mini-btn" type="primary" size="mini" @click="handleOpen">解锁</button>
					<button class="mini-btn" type="primary" size="mini" @click="handleReturn">锁车</button>
					<button class="mini-btn" @click="playAudio" type="primary" size="mini">播放</button>
				</view>

			</view>

			<view class="middle">
				日志：
				<div :class="{loader:true,show:showLoading}"></div>

			</view>
			<scroll-view class="main" scroll-y="true" scroll-with-animation :scroll-into-view="scrollIntoView">
				<view v-for="item,index in logs" :key="`logs${index}`" class="log">
					<view class="logMain">
						<view class="datetime">
							{{item.dateTime}}
						</view>
						<view class="logContent">
							<view>
								{{item.text}}
							</view>
						</view>
					</view>

					<zero-markdown-view v-if="item.result" :markdown="item.result"></zero-markdown-view>
				</view>
				<view class="bottomBlank" id="blueBottomBlank"> </view>

			</scroll-view>

			<view class="grandientView"></view>

			<view class="bottomArea">
				<view v-if="ifshowFilter" class="filterInputView">
					<input v-model="inputFilterV" @input="handleFilterInput" placeholder="输入筛选条件" />
				</view>
				<commonButton class="clearLog" @tapclick="clearLog">
					<text>清除日志</text>
				</commonButton>
				<commonButton class="filterLog" @tapclick="showFilter">
					<text>过滤</text>
				</commonButton>

			</view>
		</view>

		<Audio audioContextId="0001" :src="url" :autoPlay="true"></Audio>
	</view>
</template>

<script setup>
	import {
		nextTick,
		onMounted,
		onUnmounted,
		watch
	} from 'vue';
	import {
		parseTime
	} from '@/utils/tool.js'
	import {
		calculateBluetooth
	} from '@/api/index.js'
	import Audio from "@/components/zhangjun-xfyun/audio.vue";
	import {
		textToSpeech
	} from "@/components/zhangjun-xfyun/speech_synthesis";
	import commonButton from '@/components/commonButton.vue'
	import markdownObj from '@/components/ua-markdown/lib/uamarkdown.js'
	import bleCommand from './bleCommand.js'
	import useSystemStore from '@/store/modules/system'
	const systemStore = useSystemStore()
	const {
		dataTheme,
	} = storeToRefs(systemStore);
	//ime输入
	let imeV = ref('2490137781')
	//蓝牙token输入
	let btkV = ref('')
	let logs = ref([])
	let logs_org = ref([])
	let scrollViewHeight = ref(0)
	//搜索loading
	let showLoading = ref(false)
	//是否搜索到设备
	let deviceSearched = ref(false)
	let _markdownObj = markdownObj()
	//滚动到指定的ID位置
	let scrollIntoView = ref('')
	//滚动节流
	let scrollTimeOut = null
	//过滤输入框
	let ifshowFilter = ref(false)
	let inputFilterV = ref('')
	let url = ref('')
	let filterTimeOut = null
	watch(logs_org, (val) => {
		if (filterTimeOut) {
			clearTimeout(filterTimeOut)
		}

		filterTimeOut = setTimeout(() => {
			if (!inputFilterV.value)
				logs.value = val
			else {
				logs.value = val.filter(row => row.text.includes(inputFilterV.value) || (row.result && row
					.result.includes(inputFilterV.value)))
			}
		}, 200)

	}, {
		deep: true
	})





	//校验输入
	let validInput = () => {
		return new Promise((resolve, reject) => {
			if (!imeV.value) {
				uni.showToast({
					icon: 'none',
					title: '请输入IME'
				})
				reject(false)
			}
			// if(!btkV.value)
			// {
			// 	uni.showToast({
			// 		icon:'none',
			// 		title:'请输入btkV'
			// 	})
			// 	reject(false)
			// }
			bleCommand.setBtk(btkV.value)
			resolve(true)
		})

	}
	//过滤输入事件
	let handleFilterInput = (e) => {
		let val = e.detail.value
		if (filterTimeOut)
			clearTimeout(filterTimeOut)
		filterTimeOut = setTimeout(() => {

			if (!val)
				logs.value = logs_org.value
			else {
				logs.value = logs_org.value.filter(row => row.text.includes(val) || (row.result && row.result
					.includes(val)))
			}
		}, 200)
	}
	//显示过滤输入
	let showFilter = () => {
		ifshowFilter.value = !ifshowFilter.value
	}
	//清除日志
	let clearLog = () => {
		logs.value.length = 0
		logs_org.value.length = 0
	}
	//播放音频
	let playAudio = async () => {
		textToSpeech("人之初，性本善。性相近，习相远。苟不教，性乃迁。教之道，贵以专。昔孟母，择邻处。").then(data => {
			//console.log(234234,data);
			url.value = data
		});
		// if(!await validInput())
		// 	return
		// await bleCommand.playVoice(imeV.value, [BLE_IDX_CONFIG.START, 100]) // 播放开锁成功语音
	}
	//锁车
	let handleReturn = async () => {
		if (!await validInput())
			return
		showLoading.value = true
		deviceSearched.value = false
		// 操作蓝牙
		const openBikeResult = await bleCommand.returnBike(imeV.value, true)
		if (openBikeResult.success) {
			newLog('蓝牙开锁 --> 成功')
			deviceSearched.value = true
			// 播放开锁成功语音
			//await bleCommand.playVoice(imeV.value, [BLE_IDX_CONFIG.START, 100])

			uni.showToast({
				icon: 'success',
				title: '蓝牙开锁成功'
			})


		} else {
			newLog('蓝牙开锁 --> 失败')
			// uni.hideLoading() 
			uni.showToast({
				icon: 'error',
				title: '蓝牙开锁失败'
			})
		}
		showLoading.value = false
	}
	//解锁
	let handleOpen = async () => {

		if (!await validInput())
			return
		showLoading.value = true
		deviceSearched.value = false
		// 操作蓝牙
		const openBikeResult = await bleCommand.openBike(imeV.value, true)
		if (openBikeResult.success) {
			newLog('蓝牙开锁 --> 成功')
			deviceSearched.value = true
			// 播放开锁成功语音
			//await bleCommand.playVoice(imeV.value, [BLE_IDX_CONFIG.START, 100])

			uni.showToast({
				icon: 'success',
				title: '蓝牙开锁成功'
			})


		} else {
			newLog('蓝牙开锁 --> 失败')
			// uni.hideLoading() 
			uni.showToast({
				icon: 'error',
				title: '蓝牙开锁失败'
			})
		}
		showLoading.value = false
	}
	//插入日志
	let newLog = (data, result = null) => {
		logs_org.value.push({
			dateTime: parseTime(new Date()),
			text: data,
			result: result ? ("\n```json\n" + JSON.stringify(result)
				.replaceAll(',"', ',\n"')
				.replaceAll('{"', '{\n"')
				.replaceAll('"}', '"\n}') +
				"\n\n\n```") : null
		})

		if (logs_org.value.length > 100) {
			logs_org.value.shift()
		}


		nextTick(() => {
			//scrollIntoView.value = `blueBottomBlank`
			if (!scrollTimeOut) {
				scrollIntoView.value = `blueBottomBlank`
				scrollTimeOut = setTimeout(() => {
					clearTimeout(scrollTimeOut)
					scrollTimeOut = null
				}, 100)
			}
		})
	}
	onMounted(() => {
		uni.$on('blueLog', (data, result = null) => {
			newLog(data, result)
		})
	})
	onUnmounted(() => {
		uni.$off('blueLog')
	})
</script>

<style lang="scss" scoped>
	.bodyView {
		box-sizing: border-box;
		overflow: hidden;
	}

	.blueTest {
		overflow: hidden;
		box-sizing: border-box;
		width: 100vw;
		height: 100vh;
		@include flex-teng(column, flex-start);

		@include useTheme {
			background-color: getValue("bgColor");
			color: getValue("textColor");
		}

		padding: $mainPadding;
		row-gap: $mainPadding;

		.top {
			padding-top: 100px;
			width: 100%;

			.info {
				border-radius: 40px;
				margin-bottom: $mainPadding;
				@include flex-teng(column, flex-start);
				row-gap: 20rpx;
				padding: $mainPadding;

				@include useTheme {
					background-color: getValue("bottombgColor");
					color: getValue("textColor2");
				}

				.inputLine {
					width: 100%;
					@include flex-teng(row, flex-start);
					column-gap: 20rpx;

					.inputIME {
						width: 100%;
						border-bottom: 1px solid #fff;
					}
				}

			}

			.buttons {
				@include flex-teng;
				column-gap: 10px;
			}
		}

		.middle {
			width: 100%;
			@include flex-teng(row, flex-start);
		}

		.main {
			flex: 1;
			height: v-bind(scrollViewHeight);

			.log {
				&+.log {
					margin-top: 16rpx;
				}

				font-size: $fontSize3;

				.logMain {
					display: flex;
					column-gap: $mainPadding;

					.datetime {
						min-width: 120px;
					}
				}

			}

			.bottomBlank {
				height: 140rpx;
			}
		}

		.bottomArea {
			width: 100%;
			height: 100rpx;
			position: relative;

			@include flex-teng(row, space-evenly);

			.clearLog,
			.filterLog {
				width: 30%;
				padding: 0 $mainPadding;
				border-radius: 20px;
			}

			.filterLog {}

			.filterInputView {
				position: absolute;
				border-radius: 40px;
				transform: translate(0, -102%);
				z-index: 111;
				height: 100rpx;
				width: calc(100% - $mainPadding * 2);
				@include flex-teng(row, flex-start);
				padding: 0 $mainPadding;

				@include useTheme {
					background-color: getValue("bottombgColor");
					color: getValue("textColor2");
				}
			}
		}

		.grandientView {
			width: 100%;
			height: 200rpx;
			position: absolute;
			left: 0;
			bottom: 138rpx;
			z-index: 11;

			@include useTheme {
				background: linear-gradient(to top, getValue('bgColor'), getValue('bgColor'), getValue('bgColorReflect'), transparent);
			}
		}
	}


	.loader {
		width: 30px;
		aspect-ratio: 1;
		display: grid;
		border: 4px solid #0000;
		border-radius: 50%;
		border-color: #ccc #0000;
		animation: l16 1s infinite linear;
		opacity: 0;

		&.show {
			opacity: 1;
		}
	}

	.loader::before,
	.loader::after {
		content: "";
		grid-area: 1/1;
		margin: 2px;
		border: inherit;
		border-radius: 50%;
	}

	.loader::before {
		border-color: #f03355 #0000;
		animation: inherit;
		animation-duration: .5s;
		animation-direction: reverse;
	}

	.loader::after {
		margin: 8px;
	}

	@keyframes l16 {
		100% {
			transform: rotate(1turn)
		}
	}
</style>